  package edu.ccut.saturn.studio.logic.model.drop;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.internal.compiler.util.Util;
import org.eclipse.jdt.internal.core.JarEntryFile;
import org.eclipse.jdt.internal.core.JarPackageFragmentRoot;

import edu.ccut.saturn.studio.core.util.eclipse.SaturnBundleUtil;
import edu.ccut.saturn.studio.logic.model.xml.FileParseUtils;

public abstract class AbstarctDropHandler implements DropHandler {


	protected String getBundleName(IProject project) {
		String bundleName ="";
		StringBuffer bundleFilePath = new StringBuffer(project.getLocation().toOSString());
		bundleFilePath.append(File.separator).append("META-INF").append(File.separator).append("MANIFEST.MF");
		
		try {
			bundleName = FileParseUtils.getParseStr(bundleFilePath.toString(),
					"Bundle-SymbolicName");
		} catch (Exception e) {
			e.printStackTrace();
		}

		return bundleName;
	}

	@SuppressWarnings("restriction")
	protected String getBundleNameFromJar(JarEntryFile jarEntryFile) throws Exception {
		InputStream in1 = null;
		String bundleName = "";
		JarPackageFragmentRoot jar = (JarPackageFragmentRoot) jarEntryFile
				.getPackageFragmentRoot();
		ZipFile zipFile = null;
		try {
			zipFile = jar.getJar();
		} catch (CoreException e) {
			e.printStackTrace();
		}
		if (zipFile.getEntry("META-INF/MANIFEST.MF") != null) { //$NON-NLS-1$
			ZipEntry zipEntry = zipFile.getEntry("META-INF/MANIFEST.MF");
			if (zipEntry == null) {
				System.out.println("This is Error Dorg  ");
			}
			byte[] contents = null;
			try {
				contents = Util.getZipEntryByteContent(zipEntry, zipFile);
			} catch (IOException e) {
				e.printStackTrace();
			}
			in1 = (InputStream) new ByteArrayInputStream(contents);
//			BufferedReader bufferedReader = new BufferedReader(
//					new InputStreamReader(in1));
			bundleName = SaturnBundleUtil.getBundleAttribute(in1,
			"Bundle-SymbolicName");
//			bundleName = ParseUtil.getParseStr(bufferedReader,
//					"Bundle-SymbolicName");
			return bundleName;
		}
		return bundleName;
	}
}
